// compontents/search/index.js

import {
  KeywordModel
} from '../../models/keyword.js'
import {
  bookModel
} from '../../models/book.js'
import {
  paginationBev
} from '../behavier/pagination.js'

const KeywordMode = new KeywordModel()
const bookMode = new bookModel()
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more: {
      type: String,
      observer: function (newData) {
        if (this.data.bookKey == '') {
          return
        }
        if (newData !== '' && this.hasMore()) {
          this.setData({
            loding: true
          })
          if (this.data.moreFlage) {
            clearTimeout(this.data.moreFlage)
          }
          this.searchMore()
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWord: [],
    hotWords: [],
    bookKey: '',
    searching: false,
    moreFlage: '',
    loding: false
  },

  attached() {
    const historyWord = KeywordMode.getHistory()
    this.setData({
      historyWord: historyWord
    })
    KeywordMode.getHot((res) => {
      this.setData({
        hotWords: res.data.hot
      })
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    cancle: function () {
      this.triggerEvent('oncancle', {
        cancle: true
      })
    },
    onConfirm: function (event) {
      this.initialize()
      const q = (event.detail.value || event.detail.text).toString().trim()
      this.setData({
        searching: true,
        bookKey: q
      })
      bookMode.bookSearch(0, q, (res) => {
        this.setMoreData(res.data.books)
        this.setTotal(res.data.total)
        this.setData({
          searching: true
        })
        KeywordMode.addToHistory(q)
      })
    },
    searchShow: function () {
      this.setData({
        searching: false,
        bookKey: '',
        noData: false
      })
      //重新刷新历史搜索
      const historyWord = KeywordMode.getHistory()
      this.setData({
        historyWord: historyWord
      })
    },
    searchMore: function () {
      const length = this.getCurrenStart()
      const more = () => {
        bookMode.bookSearch(length, this.data.bookKey, (res) => {
          this.setMoreData(res.data.books)
          this.setData({
            searching: true,
            loding: false
          })
        })
      }
      //使用定时器简单做一个节流
      const moreFlage = setTimeout(more, 800)
      this.setData({
        moreFlage: moreFlage
      })
    }
  }
})
